<template>
  <app-page>
    <view style="box-sizing: border-box; width: 750rpx; height: 55px; padding-bottom: 15px; padding-left: 30rpx">
      <mxp-tabs v-model:current="currTabIndex" :list="tabList" width="690rpx" height="40px" @change="currTabIndexChange"></mxp-tabs>
    </view>
    <view v-for="(_tab, index) in tabList" :key="index">
      <view v-show="currTabIndex === index">
        <mxp-refresh-page ref="mxpRefreshPageRefs" :autoLaad="Boolean(autoLaadObj[index])" :reachBottom="true" :queryData="queryData">
          <discount-coupon v-for="coupon in dataList[currTabIndex]" :key="coupon.userCouponId" :coupon="coupon" @curClick="handleClick"></discount-coupon>
        </mxp-refresh-page>
      </view>
    </view>
    <conversion-popup ref="conversionPopupRef"></conversion-popup>
  </app-page>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { onPageScroll, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app';
  import AppPage from '@/components/app-page/app-page.vue';
  import DiscountCoupon from './components/discount-coupon.vue';
  import MxpTabs, { type $TabsItem } from '@/mxp-ui/mxp-tabs/mxp-tabs.vue';
  import { type Coupon, getDiscountCouponListAxios } from '@/api/rest';
  import MxpRefreshPage, { type Ins } from '@/mxp-ui/mxp-refresh-page/mxp-refresh-page.vue';
  import { useMescrollList } from '@/mxp-ui/mxp-tool/hooks/useHooksRefresh';
  import ConversionPopup from './components/conversion-popup.vue';

  const conversionPopupRef = ref<InstanceType<typeof ConversionPopup>>();

  const tabList: ($TabsItem & { state: 0 | 1 | 2 })[] = [
    { label: '待使用', state: 0 },
    { label: '已使用', state: 1 },
    { label: '已过期', state: 2 },
  ];
  const dataList = ref<[Coupon[], Coupon[], Coupon[]]>([[], [], []]);

  const { mxpRefreshPageRefs, currTabIndex, autoLaadObj, currTabIndexChange } = useMescrollList({ onPageScroll, onPullDownRefresh, onReachBottom });

  /**
   * 获取数据
   */
  async function queryData(ins: Ins) {
    try {
      const res = await getDiscountCouponListAxios({ couponStatus: currTabIndex.value as 0 | 1 | 2, current: ins.page, size: ins.size });
      const data: Coupon[] = res.data.records;
      dataList.value[currTabIndex.value] = ins.page > 1 ? dataList.value[currTabIndex.value]!.concat(data) : data;
      ins.setMoreSuccess(data.length, res.data.total);
    } catch (error) {
      ins.setMoreEmpty('fail_load', error.msg || '获取数据失败，BD001');
    }
  }

  /** 点击 */
  function handleClick(coupon: Coupon) {
    if (coupon.couponStatus === 0) {
      conversionPopupRef.value?.show({
        coupon,
        success() {
          useSucceed();
        },
      });
    }
  }

  /** 使用成功 */
  function useSucceed() {
    mxpRefreshPageRefs.value[0]?.startPullDownRefresh();
    mxpRefreshPageRefs.value[1]?.startPullDownRefresh();
  }
</script>

<style lang="scss" scoped>
  .list {
    box-sizing: border-box;
    width: 100%;
    padding: 0 30rpx;
    padding-top: 15px;
  }
</style>
